package lab.exec;

import java.util.Arrays;

public class RollBalance implements BalanceExecutor {

	public BalanceItem[][] balance(BalanceItem[] src, int processCount) {
		Arrays.sort(src);
		int[] sa = new int[processCount];
		int[] seq = new int[processCount];
		BalanceItem[][] ab = new BalanceItem[processCount][0];
		for (int i = 0; i < processCount; i++) {
			seq[i] = i;
		}
		for (int i = src.length - 1; i >= 0; i--) {
			int idx = seq[0];
			sa[idx] = sa[idx] + src[i].getSize();
			int length = ab[idx].length;
			BalanceItem[] _a = new BalanceItem[length + 1];
			System.arraycopy(ab[idx], 0, _a, 0, length);
			_a[length] = src[i];
			ab[idx] = _a;
			for (int j = 0; j < processCount - 1; j++) {
				if (sa[seq[j]] <= sa[seq[j + 1]]) {
					break;
				} else {
					int t = seq[j];
					seq[j] = seq[j + 1];
					seq[j + 1] = t;
				}
			}
		}
		return ab;
	}

}
